var goods = {};
/**
 * 选择商品信息
 * 在页面需要设置一个全局basePath属性
 * defaultCategory:默认选择分类ID,如果为空将默认为最顶级
 * selAfterClose:选择商品后是否关闭该商品选择框
 */
var selectGoodsDialog = null;
var selectRsGoodsData = null;
goods.selAfterClose = false;
goods.dialog = null;
goods.selectGoods = function(defaultCategory,selAfterClose, resultFunction){
	var loadUrl = basePath + "/admin/goods/selectgoods.do";
	selectRsGoodsData = resultFunction;
	goods.selAfterClose = selAfterClose;
	var dlg = $("<div/>").dialog({
		modal:true,
		header:true,
		height:500,
		width:900,
		title:"选择商品",
		closable:true,
		minimizable:false,
		collapsible:false,
		iconCls:'icon',
		loadUrl:loadUrl,
		buttons:[
		         {id:'_sel_goods_btn',text:'确  定',type:'button',iconCls:'icon-ok',handler:function(){
		        	// goods.queryGoods(\""+rowObj.id+"\")
		        	var selRow = dlg.find("#selgoods_data").jqGrid('getGridParam',"selrow");
					if(selRow == null){
						$.alert('提示','你没有选择要修改的数据!',300,140,'info');
						return;
					}
					goods.queryGoods(selRow);
		         }},
		         {text:'关  闭',type:'button',iconCls:'icon-cancel',handler:function(){
		        	 dlg.dialog("destroy");
		         }},
		         ],
		onLoad:function(){
			selectGoodsDialog = dlg;
			goods.loadGoodsTree(dlg);
			goods.getBrand(dlg,'0');
			goods.setGridData(dlg);
			dlg.find("select[name='brandId']").combo();
			dlg.find("#goods_search-btn").button({iconCls:'icon-search',handler:function(){
				var jsonParam = syscore.formToJson(dlg.find("#_goods_searchForm"));
				dlg.find("#selgoods_data").jqGrid("setGridParam",{page:1,postData:jsonParam}).trigger("reloadGrid");
			}});
			dlg.find("#goods_search-clear").button({iconCls:'icon-cancel',handler:function(){
				dlg.find("input[name='name']").val("");
				dlg.find("input[name='pinyin']").val("");
				dlg.find("input[name='styleNo']").val("");
				dlg.find("select[name='brandId']").combo("changeValue","");
				dlg.find("#goods_search-btn").trigger("click");
			}})
		}
	});
	dlg.dialog("loadPage");
	
}


goods.loadGoodsTree = function(dialog){
	var root = [{
		id:"0",
		code:'catetory_root',
		name:'商品分类信息',			
		isParent:true,
		subCategories:true,
		open:true
	}];
	$(dialog.find("#selgoods_catagoryTree")).treeview({
		treeNodeKey:'id',
		treeNodeParentKey:'parentId',
		hasChildKey:'subCategories',
		nameCol:'name',
		expandSpeed:"",
		asyncParamOther:["isPage",false],
		async:true,
		asyncUrl:function(treeNode){
			return basePath + "admin/goodscategory/list.do?parentId=" + treeNode.id;	
		},
		root:{isRoot:true,nodes:root},
		callback:{
			beforeAsyncSuccess:function(msg){
				if(msg.message.code == '-2'){
					$.alert('提示','你还没有登录或Session已经过期，请重新登录系统!',300,170,'info');
					return false;
				}
				if(msg.message.code == "-1"){
					$.alert("提示","获取信息失败，原因：" + msg.message.mess,300,170,'error');
					return false;
				}
				return true;
			},
			click:function(event,treeId,treeNode){
				var url = $(dialog.find("#selgoods_data")).jqGrid("getGridParam","url");
				goods.getBrand(dialog,treeNode.id);
				dialog.find("#selgoods_data").jqGrid("setGridParam",{"url":basePath+"admin/goods/list.do?categoryIds="+treeNode.id}).trigger('reloadGrid');
			}
		}
	});
}

/**
 * 设置商品表格信息
 */
goods.setGridData = function(dlg){
	var url = basePath + "admin/goods/list.do";
	var colNames = ['id','编码','商品名称', '商品货号','所属分类','品牌',''];
	var colModel = [
	                {name:'id',hidden:true},
	                {name:'code',index:'code', width:80,align:'left'},
				    {name:'name',index:'name', width:150,align:'left'},							 
					{name:'styleNo',index:'styleNo', width:80,align:'center'}, 
					{name:'category.name',index:'categoryName',width:100,align:'left',sortable:true},
					{name:'brand.name',index:'brandName',width:100,align:'left'},
					{name:'operator',align:'center', width:50,formatter:function(cellValue,opts,rowObj){
						return "<a href='javascript:goods.queryGoods(\""+rowObj.id+"\");' style='color:blue;text-decoration: underline;'>选择</a>";
					}}
				];
	dlg.find("#selgoods_data").jqGrid({
		url:url,
		datatype: "json",
		mtype: "POST",
		postData:{categoryIds:0,status:'normal'},
		height:347,
		multiselect:false,
		autowidth:true,
		autoencode:true,
		viewrecords:true,
		forceFit:true,
		gridview:true,
		loadui:'block',
		rowNum:0,
		sortorder:'asc',
		rownumbers:true,
		colNames:colNames,
		colModel:colModel,
		jsonReader:{
			id:'id',
			root:'result.data',
			page:'result.page.curPageNo',
			total:'result.page.totalPage',
			repeatitems:false
		},
		prmNames:{
			page:'page.curPageNo',
			rows:'page.pageSize',
			sort:'orderField',
			order:'orderType'		
		},
		page:1,
		pagerpos:'left',
		pager:dlg.find("#selgoods_page"),
		ondblClickRow:function(){
			dlg.find("#_sel_goods_btn").trigger("click");
		}
	});
}


goods.queryGoods = function(goodsId){
	url = basePath + "admin/goods/list/" + goodsId + ".do";
	if(goods.selAfterClose == true){
		var rowData = selectGoodsDialog.find("#selgoods_data").jqGrid("getRowData",goodsId);
		selectRsGoodsData(rowData,false);
		selectGoodsDialog.dialog("destroy");
		return;
	}
	
	$.post(url,"",function(rs){
		if(rs.result.data.length == 1){
			var rsDatas = new Array();
			var rsObj = {
					goodsNum:1,
					goodsPrice:0.00,
					goodsScale:100,
					goods:rs.result.data[0]
			}
			rsDatas.push(rsObj);
			selectRsGoodsData(rsDatas,true);
			selectGoodsDialog.dialog("destroy");
			return;
		}
		selectGoodsDialog.dialog("close");
		goods.genSalePropsDialog(rs.result.data);
	},"json");
}

goods.genSalePropsDialog = function(rsData){
	//var salePropKeyJson = eval('({'+rsData[0].propContext+'})');
	var salePropValueJson = eval('({' +rsData[0].propContextValue+ '})');
	var salePropVals = new Array();
	for(var val in salePropValueJson){
		salePropVals.push(val);
	}
	
	var detailUrl = basePath + "/admin/goods/selectgoodsdetail.do";
	
	var dlg = $("<div/>").dialog({
		modal:true,
		header:true,
		height:500,
		width:700,
		title:"商品销售属性",
		closable:true,
		minimizable:false,
		collapsible:false,
		iconCls:'icon',
		loadUrl:detailUrl,
		buttons:[
		         {text:'确  定',type:'button',iconCls:'icon-ok',handler:function(){
		        	 var goodsCheckeds =  dlg.find("#goods_salesProps table tbody").find("input[type='checkbox']:checked");
		        	 var cnt = goodsCheckeds.length;
		        	 if(cnt == 0){
		        		 $.alert("提示","没有选择商品信息!",300,170,'error');
		        		 return;
		        	 }
		        	 var rsDatas = new Array();
		        	 goodsCheckeds.each(function(){
		        		 var trObj = $(this).parent().parent();
		        		 var goodsNum = trObj.find(".goodsNum").val();
		        		 var goodsPrice = trObj.find(".goodsPrice").val();
		        		 var goodsScale = trObj.find(".goodsScale").val();
		        		 var data = $(this).data('goods');
		        		 var rsObj = {
		        				 goodsNum : goodsNum,
		        				 goodsPrice : goodsPrice,
		        				 goodsScale : goodsScale,
		        				 goods : data
		        		 };
		        		 rsDatas.push(rsObj);		        		 
		        	 })
		        	 selectRsGoodsData(rsDatas,false);
		        	 dlg.dialog("destroy");
		        	 selectGoodsDialog.dialog("destroy");
		         }},
		         {text:'关  闭',type:'button',iconCls:'icon-cancel',handler:function(){
		        	 dlg.dialog("destroy");
		        	 selectGoodsDialog.dialog("restore");
		         }},
		         ],
		onLoad:function(){
			var goodsStyleNo= rsData[0].goods.styleNo;
			var goodsName = rsData[0].goods.name;
			var entryUnit = rsData[0].goods.entryUnit;
			var brandName = rsData[0].goods.brand.name;
			dlg.find("#goods_name").html(goodsName);
			dlg.find("#goods_styleNo").html(goodsStyleNo);
			dlg.find("#goods_entryUnit").html(entryUnit);
			dlg.find("#goods_brand").html(brandName);
			var tableTitle = "<tr>";
			tableTitle += "<th height='30' width='18'><input type='checkbox' class='cbox' id='cb_tabledata' role='checkbox'></th>"
			for(var i in salePropVals){
				tableTitle += "<th height='30' width='100'>"+salePropVals[i]+"</th>";
			}
			tableTitle+="<th height='30'>数量</th>";
			tableTitle+="<th height='30'>单价</th>";
			tableTitle+="<th height='30'>折扣率</th>";
			tableTitle += "</tr>";
			dlg.find("#goods_salesProps table thead").html("");
			dlg.find("#goods_salesProps table thead").append(tableTitle);
			dlg.find("#goods_salesProps table th").addClass("table_title");
			dlg.find("#goods_salesProps table th").css("border","1px solid #A6C9E2");
			dlg.find("#goods_salesProps table th").css("border-left","none");
			
			dlg.find("#goods_salesProps table tbody").html("");
			for(var i = 0;i < rsData.length;i++){
				var tbody = "<tr>";
				tbody += "<td><input type='checkbox' class='cbox bodyCbox'></td>";
				var salePropKeyJson = eval('({'+rsData[i].propContext+'})');
				for(var key in salePropKeyJson){
					tbody += "<td style='padding-left:3px;'>"+salePropKeyJson[key]+"</td>";
				}
				tbody += "<td><input type='text' class='text goodsNum' style='width:98%;text-align:center;' value='1.00'></td>";
				tbody += "<td><input type='text' class='text goodsPrice' style='width:98%;text-align:center;' value='"+parseFloat(rsData[i].price).toFixed(2)+"'></td>";
				tbody += "<td><input type='text' class='text goodsScale' style='width:98%;text-align:center;' value='100.00'></td>";
				tbody += "</tr>";
				tbody = $(tbody);
				tbody.find("input[type='checkbox']").data('goods',rsData[i]);
				dlg.find("#goods_salesProps table tbody").append(tbody);
			}
			
			dlg.find("#goods_salesProps table tbody td").css("border","1px solid #A6C9E2");
			dlg.find("#goods_salesProps table tbody td").css("border-top","none");
			dlg.find("#goods_salesProps table tbody td").css("border-left","none");
			dlg.find("#goods_salesProps table").css("border-left","1px solid #A6C9E2");
			dlg.find("input[role='checkbox']").change(function(){
				if($(this).attr("checked")){
					dlg.find("#goods_salesProps table tbody").find("input[type='checkbox']").attr("checked",true);
				}else{
					dlg.find("#goods_salesProps table tbody").find("input[type='checkbox']").attr("checked",false);
				}
			});			
			dlg.find(".bodyCbox").change(function(){
				if($(this).attr("checked")){
					$(this).parent().parent().addClass("ui-state-highlight");
				}else{
					$(this).parent().parent().removeClass("ui-state-highlight");
				}
			})
			dlg.find("#goods_salesProps table tbody").find("input[type='text']").validatebox("numberFormat");
		}
	});
	dlg.dialog("loadPage");
}


goods.getBrand = function(dialog,categoryId){
	$.post(basePath + "admin/brand/list.do?categoryId=" + categoryId,"",function(rsData){
		if(rsData.message.code != '0'){
			$.alert("提示","获取品牌信息失败，原因：" + rsData.message.mess,300,170,'error');
			return;
		}
		dialog.find("select[name='brandId']").html("");
		var opt = "<option value=''>--选择品牌--</option>";
		dialog.find("select[name='brandId']").append(opt);
		for(var i = 0;i < rsData.result.data.length;i++){
			opt = "<option value='"+rsData.result.data[i].id+"'>"+rsData.result.data[i].name+"</option>";
			dialog.find("select[name='brandId']").append(opt);
		}
		dialog.find("select[name='brandId']").combo("refresh");
	},"json");			
}



//根据条码获取商品信息
goods.selectGoodsByBarcode = function(resultFunction){
	var panel = "<div>";
		panel += "<table height='100%' cellpadding='0' cellspacing='0' style='margin-left:20px;'>";
		panel += "<tr><td align='right'>条形码：</td>";
		panel += "<td align='left'><input type='text' name='barcode' class='text' size='30'/></td>" ;
		panel += "</tr>";
		panel += "</table>";
		panel += "</div>";
	var dlg = $(panel).dialog({
		height:170,
		width:300,
		title:'请输入条形码',
		iconCls:'icon',
		buttons:[
		         {id:'query_barcode_ok',text:'确 定',type:'button',iconCls:'icon-ok',handler:function(){
		        	 var barCode = dlg.find("input[name='barcode']").val();
		        	 
		        	 $.post(basePath + "admin/goods/querybybarcode.do?barCode=" + barCode,"",function(rsData){
		        			if(rsData.message.code != "0"){
		        				$.alert("提示",rsData.message.mess,300,140,"error");
		        				return;
		        			}
		        			if(rsData.result.data.length == 0){
		        				$.alert("提示","没有找到对应的商品信息!",300,140,"info");
		        				return;
		        			}
		        			var tmpData = {};
		        			if(rsData.result.data.length == 1){
		        				
		        				resultFunction(rsData.result.data[0]);
		        				dlg.dialog("destroy");
		        				return;
		        			}
		        			dlg.dialog("destroy");
		        			var detailPanel = "<div><div style='margin-top:5px;margin-left:5px;'>"+
								"<table id='detailContext_data'/>"+
								"</div></div>";
		        			var detailDialog = $(detailPanel).dialog({
		        				height:350,
		        				width:600,
		        				title:'选择商品',
		        				iconCls:'icon',
		        				buttons:[
		        				         {text:'选 择',type:'button',iconCls:'icon-ok',handler:function(){
		        				        	 var selRows = detailDialog.find("#detailContext_data").jqGrid('getGridParam',"selrow");
		        				        	 if(selRows == null){
	        									$.alert('提示','你没有选择商品信息!',300,140,'info');
	        									return;
		        				        	 }
		        				        	 var rowData = detailDialog.find("#detailContext_data").jqGrid("getRowData",selRows);
		        				        	 for(var i = 0;i < rsData.result.data.length;i++){
		        			        			if(rowData["id"] == rsData.result.data[i].id){
		        			        				detailDialog.dialog("destroy");
		        			        				resultFunction(rsData.result.data[i]);
		        			        				return;
		        			        			}
		        			        		 }
		        				         }},
		        				         {text:'取 消',type:'button',iconCls:'icon-ok',handler:function(){
		        				        	 detailDialog.dialog("destroy");
		        				         }}
		        				        ]
		        			});
		        			
		        			detailDialog.find("#detailContext_data").jqGrid({
		        				datatype:'local',
		        				height:287,
		        				width:580,
		        				forceFit:true,
		        				colNames:["id","商品名称","销售属性","单位","货号","品牌","单价"],
		        				colModel:[
		        				          {name:'id',hidden:true},
		        				          {name:'goods.name',sortable:false,width:120},
		        				          {name:'propContextValueClear',sortable:false,width:250},
		        				          {name:'goods.entryUnit',sortable:false,width:60,align:'center'},
		        				          {name:'goods.styleNo',sortable:false,width:100},
		        				          {name:'goods.brand.name',sortable:false,width:100},
		        				          {name:'price',sortable:false,width:100}
		        				          ],
		        				 multiselect:false
		        			});
		        			for(var i = 0;i < rsData.result.data.length;i++){
		        				detailDialog.find("#detailContext_data").jqGrid("addRowData",i + 1,rsData.result.data[i]);
		        			}
		        			
		        		},"json");
		         }},
		         {text:'取 消',type:'button',iconCls:'icon-cancel',handler:function(){
		        	 dlg.dialog("destroy");
		         }}
		         ]
	});
	dlg.find("input[name='barcode']").focus();
	dlg.find("input[name='barcode']").change(function(){
		dlg.find("#query_barcode_ok").trigger("click");
	})
}